package com.yxx.community.controller;

import com.yxx.community.dto.CommentCreatrDTO;
import com.yxx.community.dto.CommentDTO;
import com.yxx.community.dto.ResultDTO;
import com.yxx.community.enums.CommentTypeEnum;
import com.yxx.community.exception.CustomizeErrorCode;
import com.yxx.community.model.Comment;
import com.yxx.community.model.User;
import com.yxx.community.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: YuXinXin
 * @Description:
 * @Date:Created in 16:17 2020/2/6
 **/
@Controller
public class CommentController {

  @Autowired
  private CommentService commentService;

  @ResponseBody
  @PostMapping("/comment")
  public Object post(@RequestBody CommentCreatrDTO commentCreatrDTO,
                     HttpServletRequest request) {
    User user = (User) request.getSession().getAttribute("user");
    if (user == null) {
      return ResultDTO.errorof(CustomizeErrorCode.NO_LOGIN);
    }
    if (commentCreatrDTO == null || StringUtils.isEmpty(commentCreatrDTO.getContent())) {
      return ResultDTO.errorof(CustomizeErrorCode.COMMENT_IS_EMPTY);
    }
    Comment comment = new Comment();
    comment.setParentId(commentCreatrDTO.getParentId());
    comment.setType(commentCreatrDTO.getType());
    comment.setContent(commentCreatrDTO.getContent());
    comment.setGmtCreate(System.currentTimeMillis());
    comment.setGmtModified(comment.getGmtCreate());
    comment.setCommentator(user.getId());
    comment.setLikeCount(0L);
    comment.setSubComment(0);
    commentService.insert(comment,user);
    return ResultDTO.okof();
  }


    @ResponseBody
  @GetMapping("/comment/{id}")
  public ResultDTO<List<CommentDTO>> comments(@PathVariable("id") Long id){
    List<CommentDTO> commentDTOS = commentService.listByTargetId(id, CommentTypeEnum.COMMENT);
    return ResultDTO.okof(commentDTOS);
  }
}
